package com.zl.csMall.mine.history.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zl.csMall.mine.history.mapper.HistoryMapper;
import com.zl.csMall.mine.history.po.History;
import com.zl.csMall.mine.history.service.HistoryService;
import com.zl.csMall.util.Util;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description: HistoryServiceImpl
 * @author: ChenNing
 * @date 2025-10-21 11:35
 */
@Service
public class HistoryServiceImpl extends ServiceImpl<HistoryMapper, History> implements HistoryService {


    @Override
    public boolean addHistory(long userId, long commodityId) {
        // 判断该用户是否浏览过该商品
        LambdaQueryWrapper<History> historyQuery = new LambdaQueryWrapper<>();
        historyQuery.select(History::getId)
                .eq(History::getUserId, userId)
                .eq(History::getCommodityId, commodityId);
        History oldHistory = this.getOne(historyQuery, false);
        if (oldHistory == null || oldHistory.getId() == 0){
            // 未浏览过该商品，新增浏览记录
            return this.save(new History(Util.getUuId(), userId, commodityId, new Date()));
        } else {
            // 浏览过该商品，更新创建时间
            oldHistory.setCreateDate(new Date());
            return this.updateById(oldHistory);
        }
    }

    @Override
    public Page getUserIdByCommodityId(long commodityId, Page page) {
        List<Long> userIdList = new ArrayList<>();

        LambdaQueryWrapper<History> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(History::getUserId)
                .eq(History::getCommodityId, commodityId)
                .orderByDesc(History::getCreateDate);
        page = this.page(page, queryWrapper);
        List<History> historyList = page.getRecords();
        if (historyList == null || historyList.size() < 1){
            return page.setRecords(userIdList);
        }
        for (History history : historyList){
            userIdList.add(history.getUserId());
        }
        return page.setRecords(userIdList);
    }

}
